# D:\dazuoye\app\views\sales_churn.py

from flask import Blueprint, jsonify
# 【已更新】导入 sales_performance_data 以支持桑基图
from app.data_loader import customer_purchase_data, customer_churn_data, sales_performance_data
import pandas as pd

churn_bp = Blueprint('sales_churn', __name__)


# --- API 接口 ---

@churn_bp.route('/api/sales/customer_frequency_heatmap', methods=['GET'])
def get_customer_frequency_heatmap():
    """【方案A】API: 客户个人购买频率热区图 (返回Top 100客户数据)"""
    if customer_purchase_data is None:
        return jsonify({"error": "客户购买数据未能加载"}), 500
    try:
        df = customer_purchase_data[['客户ID', '购买频率(天)']].dropna()
        df_top100 = df.nlargest(100, '购买频率(天)')
        result = df_top100.rename(columns={'客户ID': 'name', '购买频率(天)': 'value'}).to_dict(orient='records')
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": f"生成热区图数据时出错: {e}"}), 500


@churn_bp.route('/api/sales/churn_risk_matrix', methods=['GET'])
def get_churn_risk_matrix():
    """【方案A】API: 客户流失风险矩阵图 (返回数据)"""
    if customer_purchase_data is None or customer_churn_data is None:
        return jsonify({"error": "客户数据未能加载"}), 500
    try:
        df_merged = pd.merge(customer_purchase_data, customer_churn_data, on='客户ID', how='inner')
        result_df = df_merged[['客户终身价值', '流失概率', '流失风险', '平均订单价值']]
        return jsonify(result_df.to_dict(orient='records'))
    except Exception as e:
        return jsonify({"error": f"生成流失风险矩阵数据时出错: {e}"}), 500


# 【新增】将桑基图逻辑移动到此文件
@churn_bp.route('/api/sales/channel_to_product_sankey', methods=['GET'])
def get_channel_to_product_sankey():
    """【方案A】API: 从渠道到产品的销售额分布桑基图 (返回数据)"""
    if sales_performance_data is None:
        return jsonify({"error": "销售业绩数据未能加载"}), 500
    try:
        df = sales_performance_data[['渠道', '产品ID', '总交易额(GMV)']].dropna()
        df_top = df.groupby('渠道', group_keys=False).apply(lambda x: x.nlargest(5, '总交易额(GMV)'))

        all_nodes = pd.concat([df_top['渠道'], df_top['产品ID']]).unique()
        nodes = [{"name": name} for name in all_nodes]

        links = df_top.rename(columns={'渠道': 'source', '产品ID': 'target', '总交易额(GMV)': 'value'}).to_dict(
            orient='records')

        return jsonify({"nodes": nodes, "links": links})
    except Exception as e:
        return jsonify({"error": f"生成渠道桑基图数据时出错: {e}"}), 500